import tkinter as tk
from tkinter import filedialog
import os
from PyPDF2 import PdfReader, PdfWriter
from tkinter.ttk import Progressbar

def add_directory():
    file_type = file_type_var.get()  # 获取选择的文件类型
    dir_path = filedialog.askdirectory()
    if dir_path:
        file_listbox.delete(0, tk.END)
        for root, dirs, files in os.walk(dir_path):
            for file in files:
                if file_type == "*.pdf" and file.lower().endswith('.pdf'):
                    file_listbox.insert(tk.END, os.path.join(root, file))
                elif file_type == "*.doc" and file.lower().endswith('.doc'):
                    file_listbox.insert(tk.END, os.path.join(root, file))
                elif file_type == "*.docx" and file.lower().endswith('.docx'):
                    file_listbox.insert(tk.END, os.path.join(root, file))


def remove_selected_files():
    selected_indices = file_listbox.curselection()
    # 倒序删除，避免索引变化导致删除错误
    for index in sorted(selected_indices, reverse=True):
        file_listbox.delete(index)


def merge_pdfs_with_bookmarks():
    output_name = output_name_entry.get()
    if not output_name.endswith(".pdf"):
        output_name += ".pdf"
    output_path = output_path_var.get()
    if output_path == "自定义":
        output_path = filedialog.asksaveasfilename(defaultextension=".pdf")
    else:
        output_path = filedialog.askdirectory() + "/" + output_name

    try:
        writer = PdfWriter()
        bookmarks = []
        total_pages = 0
        pdf_files = [file_listbox.get(i) for i in range(file_listbox.size()) if file_listbox.get(i).lower().endswith('.pdf')]

        progress_bar['maximum'] = len(pdf_files)
        progress_bar['value'] = 0

        for idx, file_path in enumerate(pdf_files):
            with open(file_path, 'rb') as file:
                reader = PdfReader(file)
                for page_num in range(len(reader.pages)):
                    writer.add_page(reader.pages[page_num])
            bookmark_title = os.path.splitext(os.path.basename(file_path))[0]
            bookmark_page = total_pages
            bookmarks.append((bookmark_title, bookmark_page))
            total_pages += len(reader.pages)
            progress_bar['value'] = idx + 1
            root.update_idletasks()

        for title, page_num in bookmarks:
            writer.add_outline_item(title, page_num)

        with open(output_path, 'wb') as f:
            writer.write(f)
        tk.messagebox.showinfo("成功", "PDF文件已成功合并！")
    except Exception as e:
        tk.messagebox.showerror("错误", str(e))


root = tk.Tk()
root.title("文件合并工具")
root.geometry("500x500")

# 点击添加文件或拖拽至此区域
# add_file_label = tk.Label(root, text="点击添加文件 或 拖拽至此区域")
# add_file_label.pack()

# 输入路径
input_by_frame = tk.Frame(root)
input_by_frame.pack()
# 添加目录按钮
add_directory_button = tk.Button(input_by_frame, text="添加目录", command=add_directory)
add_directory_button.pack(side=tk.LEFT)

# 文件类型选择下拉框
file_type_var = tk.StringVar()
file_type_var.set("*.pdf")
file_type_options = ["*.pdf", "*.doc", "*.docx"]
file_type_dropdown = tk.OptionMenu(input_by_frame, file_type_var, *file_type_options)
file_type_dropdown.pack(side=tk.LEFT)

# 删除文件按钮
remove_button = tk.Button(input_by_frame, text="删除文件", command=remove_selected_files)
remove_button.pack(side=tk.LEFT)

# 文件列表框，设置宽度为400
file_listbox = tk.Listbox(root, width=400)
file_listbox.pack()

# # 排序方式
# sort_by_frame = tk.Frame(root)
# sort_by_frame.pack()
# sort_by_name = tk.Radiobutton(sort_by_frame, text="按文件名", value="name")
# sort_by_name.pack(side=tk.LEFT)
# sort_by_time = tk.Radiobutton(sort_by_frame, text="按创建时间", value="time")
# sort_by_time.pack(side=tk.LEFT)

# # 统一页面大小
# unify_size = tk.Checkbutton(root, text="统一页面大小", onvalue=True, offvalue=False)
# unify_size.pack()
# size_option = tk.StringVar()
# size_option.set("A4")
# size_menu = tk.OptionMenu(root, size_option, "A4", "A3", "Letter")
# size_menu.pack()

# 输出名称和路径
output_by_frame = tk.Frame(root)
output_by_frame.pack()

output_name_label = tk.Label(output_by_frame, text="输出文件名:")
output_name_label.pack(side=tk.LEFT)

output_name_entry = tk.Entry(output_by_frame)
output_name_entry.insert(0, "合并文件")
output_name_entry.pack(side=tk.LEFT)

output_path_frame = tk.Frame(root)
output_path_frame.pack()
output_path_var = tk.StringVar()
output_path_var.set("原文件夹")


output_path_original = tk.Radiobutton(output_path_frame, text="原文件夹", variable=output_path_var, value="原文件夹")
output_path_original.pack(side=tk.LEFT)

output_path_custom = tk.Radiobutton(output_path_frame, text="自定义", variable=output_path_var, value="自定义")
output_path_custom.pack(side=tk.LEFT)
browse_btn = tk.Button(output_path_frame, text="浏览", command=lambda: filedialog.askdirectory())
browse_btn.pack(side=tk.LEFT)

# 进度条
progress_bar = Progressbar(root, orient=tk.HORIZONTAL, length=300, mode='determinate')
progress_bar.pack()

# 开始合并按钮
merge_btn = tk.Button(root, text="开始合并", command=merge_pdfs_with_bookmarks)
merge_btn.pack()

root.mainloop()